#include <stdio.h>
#include <sys/epoll.h>
#include <stdint.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include "reactor.h"
#include "event.h"
#include "common.h"
#include "connecteh.h"

event_handler_t *create_connecteh(int connfd,reactor_t *reactor){
	event_handler_t *eh;
	eh = (event_handler_t *)malloc(sizeof(event_handler_t));
	if(eh == NULL){
		outputError(errno,"%s","malloc event_handler_t");
	}
	eh->fd = connfd;
	eh->handle_event = handle_event;
	eh->reactor = reactor;

	return eh;
}

static void *handle_event(void *msg){
	handle_event_msg_t *arg;
	int fd,readN;
	char buf[BUF_SIZE];

	arg = (handle_event_msg_t *)msg;
	fd = arg->fd;

	if(arg->events & EPOLLRDHUP){
		close(fd);
	}else{
		while((readN = read(fd,buf,BUF_SIZE)) > 0){
			if(write(fd,buf,readN) != readN){
				outputError(errno,"%s","write error");
			}
		}
	}
}
